<template>
  <div>
    <!-- 头部：搜索框 -->
    <el-row>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="工作流名称">
          <el-input v-model="searchForm.flowName" placeholder="工作流名称"></el-input>
        </el-form-item>
        <el-form-item label="创建人名称">
          <el-input v-model="searchForm.createUserName" placeholder="工作流创建人名称"></el-input>
        </el-form-item>
        <el-form-item label="创建人账号">
          <el-input v-model="searchForm.createUserName" placeholder="工作流创建人账号"></el-input>
        </el-form-item>
        <el-form-item label="流程状态">
          <el-select v-model="searchForm.deployStatus" clearable placeholder="请选择工作流状态">
            <el-option
              v-for="item in deployStatusSelectOptionList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程上传时间">
          <el-date-picker
            v-model="searchForm.uploadTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00']"
          </el-date-picker>
        </el-form-item>  
        <el-form-item label="流程部署时间">
          <el-date-picker
            v-model="searchForm.deployTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            :default-time="['00:00:00']"
          </el-date-picker>
        </el-form-item>  
      </el-form>
    </el-row>
    <el-row>
      <el-col  :span="2" :offset="22">
        <el-button size="small" type="primary" @click="getDeployInfoPageList">查询</el-button>
        <el-button size="small" type="primary" @click="resetSearchForm">重置</el-button>
      </el-col>
    </el-row>


    <el-button
      size="small"
      type="primary"
      @click="uploadDialogVisible = true"
      >上传工作流</el-button
    >
    <el-button size="small" type="primary">批量部署</el-button>
    <el-button size="small" type="danger">批量删除</el-button>

    <!-- 中部表格 -->
    <el-row>
      <el-table :data="deployedDataList" border style="width: 100%">
        <el-table-column
          type="selection"
          width="50">
        </el-table-column>
        <el-table-column fixed prop="flowName" label="工作流名称" width="150">
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="200">
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="200">
        </el-table-column>
        <el-table-column prop="deployTime" label="部署时间" width="200">
        </el-table-column>
        <el-table-column prop="city" label="创建人名称" width="150">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="300">
        </el-table-column>
        <el-table-column prop="deployStatus" :formatter="deployStatusFormat" label="状态" width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="deployAct(scope.row)" v-if="!checkActRunningStatus(scope.row.deployStatus)">部署</el-button>
            <el-button @click="showFlowPicBtn(scope.row)" type="text" size="small">查看</el-button>
            <el-button type="text" size="small" @click="editUploadInfo(scope.row)" v-if="!checkActRunningStatus(scope.row.deployStatus)">编辑</el-button>
            <el-button type="text" size="small" v-if="!checkActRunningStatus(scope.row.deployStatus)" @click="delDeploy(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page=searchFormPageInfo.pageNum
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchFormPageInfo.pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total= searchFormPageInfo.total
  >
      </el-pagination>
    </el-row>

    <!-- 编辑工作流信息的弹框 -->
    <el-dialog
      :title= deployInfoFormTitle
      :visible="uploadDialogVisible"
      width="30%"
      center
      :before-close = "closedDialog"
    >
      <el-form
        label-width="100px"
        class="demo-ruleForm"
        :model="deployInfoVO"
      >
        <el-form-item label="流程名称" prop="flowName">
          <el-input v-model="deployInfoVO.flowName"></el-input>
        </el-form-item>
        <el-form-item label="流程标识" prop="flowKey">
          <el-input v-model="deployInfoVO.flowKey"></el-input>
        </el-form-item>

        <el-form-item label="流程文件">
          <el-upload
            :multiple="false"
            :limit="3"
            ref="upload"
            action=""
            :file-list="fileList"
            :on-success="success"
            :on-error="errorUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              type="primary"
              @click="submitUpload"
              >上传到服务器<i class="el-icon-upload el-icon--right"></i
            ></el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="deployInfoVO.remark"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSaveDeployInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 显示工作流示意图的弹框 -->
    <el-dialog
      title="提示"
      :visible="flowPicDigVisible"
      width="30%"
      >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="flowPicDigVisible = false">取 消</el-button>
        <el-button type="primary" @click="flowPicDigVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";
import { deployedList, saveDeployInfo, deploy, deleteDeploy } from "@/api/configActiviti/deploy.js";
import { checkActRunning } from "@/api/activiti/common.js";

export default {
  name: "Deploy",
  data() {
    return {
      // 搜索表单分页参数
      searchFormPageInfo : {
        // 当前页
        pageNum: 1,
        // 每页显示条数
        pageSize: 10,
        // 总数
        total: 0,
      },
      // 搜索表单
      searchForm : {
        // 表单名称
        flowName : '',
        // 创建人名称
        createUserName:'',
        // 流程部署状态
        deployStatus:'',
        uploadTimeRange: '',
        deployTimeRange: '',

        // 分页
        pageNum: 1,
        pageSize: 10,
      },
      // 默认搜索表单
      defaultSearchForm  : {
        // 表单名称
        flowName : '',
        // 创建人名称
        createUserName:'',
        // 流程部署状态
        deployStatus:'',
        uploadTimeRange: '',
        deployTimeRange: '',

        // 分页
        pageNum: 1,
        pageSize: 10,
      },


      // 表单搜索框工作流下拉框
      deployStatusSelectOptionList: [
        { value: '0', label: '已上传' },
        { value: '1', label: '已部署' },
        { value: '2', label: '运行中' },
      ],


      // ===========================begin 查看工作流图形data
      // 工作流示意图弹框
      flowPicDigVisible: false,

      // ===========================end 查看工作流图形data

      // 流程文件上传表单
      uploadDialogVisible: false,

      fileList: [], // 定义一个上传文件的空数组

      // 工作流列表
      deployedDataList: [],

      deployInfoFormTitle : '保存工作流信息',

      deployInfoVO: {
        id: "",
        createTime: "",
        updateTime: "",
        flowName: "",
        flowKey: "",
        deployId: "",
        remark: "",
        // 文件信息
        fileUpDowmInfoVO: { 
          id: "",
          fileRelId:"",
          fileName: "", 
          modelName: "" 
        },
        fileInfoId: ""
      },
    };
  },
  methods: {
    //=================================业务方法=================================
    /**
     * 检查工作流是否在运行中
     * @param code 状态码
     */
    checkActRunningStatus(code) {
      return checkActRunning(code);
    },

    /**
     * 状态格式化
     */
    deployStatusFormat(row, column) {
      this.checkActRunningStatus(row.deployStatus);
      if (row.deployStatus == 0) {
        return "已上传";
      } else if (row.deployStatus == 1) {
        return "已部署";
      } else if (row.deployStatus == 2) {
        return "运行中";
      }
    },

    //=================================绑定按钮事件=================================
    /**
     * 查询表单重置
     */
    resetSearchForm() {
      this.searchForm = this.defaultSearchForm;
    },

    /**
     * 删除部署
     * @param deployInfo 部署信息
     */
    delDeploy(deployInfo) {
      this.$confirm('删除工作流【'+ deployInfo.flowName + '】, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          deleteDeploy([deployInfo.id]).then(response => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getDeployInfoPageList();
            }else {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }
    
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    // begin 查看工作流图形method
    /**
     * 显示工作流示意图弹框绑定
     */
    showFlowPicBtn(deployInfo) {
      this.flowPicDigVisible = true;
    },

    // end 查看工作流图形method

    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。function(file, fileList)
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },

    success(response, file, fileList) {
      console.log("1");
    },
    errorUpload(err, file, fileList) {
      console.log(err);
    },
    // 上传文件到服务器
    submitUpload() {
      //判断是否有文件，再上传
      if (this.fileList.length === 0) {
        return this.$message.warning("请选取文件后再上传");
      }
      const formData = new FormData();
      this.fileList.forEach((file) => {
        formData.append("fileList", file.raw);
      });

      request({
        method: "POST",
        url: "/deploy/uploadProcess",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then((res) => {
          if (res.success == true) {
            console.log(res.data);

            //绑定文件
            this.deployInfoVO.fileUpDowmInfoVO.id = res.data[0].id
            this.deployInfoVO.fileUpDowmInfoVO.fileName = res.data[0].fileName
            

            this.$message.success("文件上传成功");
          } else {
            this.$message.error("文件上传失败");
          }
          
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    

    // 保存部署信息
    submitSaveDeployInfo() {
      //formData.set("person",  new Blob([JSON.stringify({"name:": "dsq", "age":18, "sex": "dsd"})], { type: "application/json" }));

      // 1.上传表单文件
      saveDeployInfo(this.deployInfoVO)
        .then((res) => {
          if (res.code == 200) {
            console.log(res.data);
            this.$message.success("保存成功");
          } else {
            this.$message.error("保存失败");
          }
          //清空fileList
          this.fileList = [];
        })
        .catch(function (error) {
          console.log(error);
        });

      // 2.清空表单文件
      this.closedDialog()

      // 3.隐藏弹框

      // 4.查询列表
      this.getDeployInfoPageList();
    },
    closedDialog() {
      // 清空表单文件
      this.deployInfoVO = {};
      //清空fileList
      this.fileList = [];
      this.uploadDialogVisible = false;

    },

    // 编辑
    editUploadInfo(data) {
      console.log(data);

      // 回显数据
      this.deployInfoVO = data

      // 显示弹框
      this.uploadDialogVisible = true
    },

    deployAct(data) {
      let deployInfoIdList = [];
      deployInfoIdList.push(data.id)

      deploy(deployInfoIdList)
      .then((res) => {
          if (res.code == 200) {
            console.log(res.data);
            this.$message.success("部署成功");
          } else {
            this.$message.error("部署失败");
          }
          //清空fileList
          this.fileList = [];
        }).catch(function (error) {
          console.log(error);
        });

      
    },

    //========================================================
    // 查询工作流列表
    getDeployInfoPageList() {
      console.log("我" +this);
      deployedList(this.searchForm).then((response) => {
        if (response.success === true) {
          if(!response.data) {
            return
          }
          this.deployedDataList = response.data.dataList ;
          this.searchFormPageInfo.pageNum = response.data.pageNum;
          this.searchFormPageInfo.pageSize = response.data.pageSize;
          this.searchFormPageInfo.total = response.data.total;
        }
        
      });
    },
  },

  mounted() {
    let that= this;//将vue对象的引用保存在that中
    console.log("mounted:" + that);
    this.getDeployInfoPageList();
  },
};
</script>

<style scope>
</style>
